package org.timeticker;

import org.apache.log4j.Logger;
import org.timeticker.gui.MainWindow;
import org.timeticker.gui.TrayIconSupport;

/**
 * Application entry point
 *
 * @author Ivan Latysh
 * @version 0.1
 * @since 10-Jul-2007 : 12:27:33 AM
 */
public class Main {

  /** Main class instance */
  public static final Main main = new Main();

  /** Component logger */
  protected Logger logger = Logger.getLogger(this.getClass().getName());

  /** Application configuration */
  public Configuration configuration;
  /** Application main window */
  protected MainWindow mainWindow;
  /** Tray Icon support */
  protected TrayIconSupport tray;

  /**
   * Initialize application
   */
  public void initApplication(){
    // load configuration
    loadConfiguration();
    // initialize TimeTicker
    Timekeeper.getInstance().initialize();
    // register tray icon
    registerTrayIcon();
    // create main window
    createMainWindow();
  }

  /**
   * Register application tray icon 
   */
  public void registerTrayIcon() {
    if (null==tray) tray = new TrayIconSupport();

    if (tray.isTrayIconSupported()) {
      try {
        tray.registerTrayIcon();
      } catch (Exception e) {
        logger.error("Unable to register application tray icon", e);
      }
    }
  }

  /**
   * Return main window instane
   *
   * @return main window instance
   */
  public MainWindow getMainWindow() {
    return mainWindow;
  }

  /**
   * Create and display the main window
   *
   * @return just created main window
   */
  public MainWindow createMainWindow() {
    // create the main window
    mainWindow = new MainWindow();
    // @TODO load and set window geometry
    // show the window
    mainWindow.setVisible(true);
    // return just created main window
    return mainWindow;
  }

  /**
   * Destroy main window
   */
  public void destroyMainWindow() {
    if (null!=mainWindow) {
      mainWindow.setVisible(false);
      mainWindow.dispose();
    }
  }

  /**
   * Destroy application
   */
  public void detroyApplication() {
    // destroy TimeTicker
    Timekeeper.getInstance().destroy();
    // destoroy tray icon
    tray.unregisterTrayIcon();
    // force VM to shutdown
    System.exit(0);
  }

  /**
   * Load application configuration
   */
  private void loadConfiguration() {
//    configuration = new Configuration();
  }

  /**
   * Application entry point
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    // load configuration
    main.loadConfiguration();
    // init application
    main.initApplication();
  }

}
